package com.itmayiedu.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.config.AlipayConfig;
import com.itmayiedu.api.service.PayService;
import com.itmayiedu.base.BaseApiService;
import com.itmayiedu.base.ResponseBase;
import com.itmayiedu.constants.Constants;
import com.itmayiedu.dao.PaymentInfoDao;
import com.itmayiedu.entity.PaymentInfo;
import com.itmayiedu.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author cht 【wonderfor@vip.qq.com】
 * @Date 2018/10/31
 */
@RestController
public class PaySerivceImpl extends BaseApiService implements PayService{

    @Autowired
    PaymentInfoDao paymentInfoDao;

    @Override
    public ResponseBase createToken(@RequestBody PaymentInfo paymentInfo) {
        //1.验证参数

        //2.创建支付信息
        Integer savePaymentType = paymentInfoDao.savePaymentType(paymentInfo);
        if(savePaymentType<=0) {
            return setResultError("创建支付订单失败");
        }
        //3.生成对应token
        String payToken = TokenUtils.getPayToken();
        //4.存在redis中,key为token,value为支付id
        baseRedisService.setString(payToken, paymentInfo.getId()+"", Constants.PAY_TOKEN_MEMBER_TIME);
        //5.返回token
        JSONObject data = new JSONObject();
        data.put("payToken", payToken);
        return setResultSuccess(data);
    }

    @Override
    public ResponseBase findPayToken(@RequestParam("payToken") String payToken) {
        //1.参数验证
        if(StringUtils.isEmpty(payToken)) {
            return setResultError("token不能为空");
        }
        //2.参数token验证
        //3.使用token 查找 redis 找到对应id
        String payId = baseRedisService.getString(payToken);
        if(StringUtils.isEmpty(payId)) {
            return setResultError("支付请求已经超时");
        }
        //4.使用支付id,进行下单
        Long payIDL= Long.parseLong(payId);
        //5.使用支付id查询支付信息
        PaymentInfo paymentInfo = paymentInfoDao.getPaymentInfo(payIDL);
        if(paymentInfo == null) {
            return setResultError("未找到支付信息");
        }
        //6.对接支付代码,返回提交支付form表单元素给客户端

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = paymentInfo.getOrderId();
        String total_amount = paymentInfo.getPrice()+"";
        String subject ="坚果课堂课时包";
        String body =  "坚果课堂";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //请求
        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            JSONObject data = new JSONObject();
            data.put("payHtml", result);
            return setResultSuccess(data);
        } catch (AlipayApiException e) {
            return setResultError("支付异常");
        }

    }


}

